<?php

namespace App\Dao;

use App\Model\ChatsModel;

class ChatsDao extends BaseDao
{
    public static function builder_query($params = []): \Illuminate\Database\Eloquent\Builder
    {
        $query = ChatsModel::query();

        $query->when(checkIsHasField($params,'user_id'),function ($query)use ($params){
            $query->where('user_id',$params['user_id']);
        });

        $query->when(checkIsHasField($params,'chat_id'),function ($query)use ($params){
            $query->where('chat_id',$params['chat_id']);
        });


        return $query;
    }


    public static function add_chats($params = [])
    {
        if(!checkIsHasField($params,'type')){
            self::error('请选择类型');
        }
        if(!checkIsHasField($params,'message')){
            self::error('请上传信息');
        }
        if(UsersDao::builder_user_query(['user_id'=>$params['user_id']])->value('message') == 1){
            self::error('已被禁言');
        }



        if(self::builder_query()->create($params) === false){
            self::error('评论失败');
        }
    }

    public static function chats(array $params): \Illuminate\Contracts\Pagination\LengthAwarePaginator
    {
        return self::builder_query($params)->orderByDesc('sorts')->orderByDesc('created_at')->paginate();
    }

    public static function chatsPageinate(array $all)
    {
        return self::builder_query($all)
            ->orderByDesc('sorts')
            ->orderByDesc('created_at')
            ->paginate();
    }

    public static function del(array $array)
    {
        if(self::builder_query(['chat_id'=>$array['chat_id']])->delete() === false){
            self::error('删除失败');
        }
    }

    public static function info(array $all)
    {
        return self::builder_query($all)->first()->toArray();
    }

    public static function editInfo(array $params)
    {
        if (self::builder_query(['chat_id'=>self::deleteParamId($params,'chat_id')])->update(self::filterFields($params,new ChatsModel())) === false){
            self::error('设置失败');
        }
    }
}
